package com.example.myapplicationchat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class share extends Activity {
    private static final int REQUEST_STORAGE_PERMISSIONS = 1;
    private final int REQUEST_CAMERA = 1001;
    private final int REQUEST_PHOTO_PICKER = 1002;
    private final int REQUEST_VIDEO_PICKER = 1003;

    private EditText postContentEt;
    private ImageView addImageIv;
    private ImageView addPhotoIv;
    private ImageView addVideoIv;
    private RecyclerView selectedItemRv;
    private Button postBtn;

    private List<String> selectedItems;
    private SelectedItemAdapter adapter;
    private File imageFile;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share1);
        
        // Request storage permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSIONS);
        }

        postContentEt = findViewById(R.id.post_content_et);
        addImageIv = findViewById(R.id.add_image_iv);
        addPhotoIv = findViewById(R.id.add_photo_iv);
        addVideoIv = findViewById(R.id.add_video_iv);
        selectedItemRv = findViewById(R.id.selected_item_rv);
        postBtn = findViewById(R.id.post_btn);

        selectedItems = new ArrayList<>();
        adapter = new SelectedItemAdapter(this, selectedItems);
        selectedItemRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        selectedItemRv.setAdapter(adapter);

        addImageIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    imageFile = createImageFile();
                    Uri photoURI = FileProvider.getUriForFile(share.this, "com.example.fileprovider", imageFile);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                    startActivityForResult(takePictureIntent, REQUEST_CAMERA);
                }
            }
        });

        addPhotoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, REQUEST_PHOTO_PICKER);
            }
        });

        addVideoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent videoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                videoPickerIntent.setType("video/*");
                startActivityForResult(videoPickerIntent, REQUEST_VIDEO_PICKER);
            }
        });

        postBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 发布帖子
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_CAMERA:
                    if (imageFile == null || !imageFile.exists()) {
                        Toast.makeText(this, "Failed to get the photo", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    selectedItems.add(imageFile.getAbsolutePath());
                    adapter.notifyDataSetChanged();
                    break;
                case REQUEST_PHOTO_PICKER:
                    Uri uri = data.getData();
                    if (uri != null && uri.getPath() != null) {
                        selectedItems.add(uri.getPath());
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case REQUEST_VIDEO_PICKER:
                    Uri videoUri = data.getData();
                    if (videoUri != null && videoUri.getPath() != null) {
                        selectedItems.add(videoUri.getPath());
                        adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + ".jpg";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {
            return File.createTempFile(imageFileName, "", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}